/*
Copyright (c) 2010 Safe Creative (http://www.safecreative.org)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
 */
package com.digiregistry.api.wrapper.converters;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.javabean.BeanProvider;
import com.thoughtworks.xstream.converters.javabean.JavaBeanProvider.Visitor;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * XStream base converter class
 *
 * @author mpolo@safecreative.org
 * @author jguillo@safecreative.org
 */
public class ModelConverter implements Converter {
    private static Logger log = LoggerFactory.getLogger(ModelConverter.class);
    
    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
	private Class clazz;
	private Map<String, Class> propertyClass = new HashMap<String, Class>();
	private Map<String, Method> getMethods = new HashMap<String, Method>();
	private Map<String, Method> setMethods = new HashMap<String, Method>();
	
	public ModelConverter(Class clazz) {
		this.clazz = clazz;
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
				String propertyName = property.getName();
				propertyClass.put(propertyName, property.getPropertyType());
				getMethods.put(propertyName, property.getReadMethod());
				setMethods.put(propertyName, property.getWriteMethod());
			}
		}
		catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public boolean canConvert(Class type) {
		return type.equals(clazz);
	}

	public String getAlias() {
		return clazz.getSimpleName().toLowerCase();
	}
	
	public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
		BeanProvider bp = new BeanProvider();
		bp.visitSerializableProperties(source, new Visitor() {
			
			public void visit(String name, Class type, Class definedIn, Object value) {
				marshalFieldValue(context, writer, name, value);
			}
			
			public boolean shouldVisit(String name, Class definedIn) {
				return true;
			}
		});
	}
	
	protected void marshalField(MarshallingContext context, HierarchicalStreamWriter writer, Object obj, String fieldName) {
		try {
			Object value = getFieldValue(obj, fieldName);
			marshalFieldValue(context, writer, fieldName, value);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected Object getFieldValue(Object obj, String fieldName) throws InvocationTargetException {
		try {
			return getMethods.get(fieldName).invoke(obj);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected void marshalFieldValue(MarshallingContext context, HierarchicalStreamWriter writer, String fieldName, Object value) {
		if (value != null) {
			writer.startNode(fieldName);
			context.convertAnother(value);
			writer.endNode();
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		try {
			Object result = clazz.newInstance();
	        while (reader.hasMoreChildren()) {
	            reader.moveDown();
	
	            String propertyName = reader.getNodeName();
	            Object value = context.convertAnother(result, getFieldClass(propertyName));
	            setFieldValue(result, propertyName, value);

	            reader.moveUp();
	        }
	
	        return result;
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected Object setFieldValue(Object obj, String fieldName, Object value) {
		try {
			return setMethods.get(fieldName).invoke(obj, value);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	protected Class getFieldClass(String fieldName) {
		try {
			return propertyClass.get(fieldName);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}
